/**
 * API client for Gitee search integration
 */

import axios, { AxiosInstance, AxiosError } from 'axios';
import { SearchParams, GiteeAPIParams, GiteeSearchResponse, GiteeAPIError, GiteeAPITimeoutError, GiteeAPIRateLimitError } from '../types.js';

export class GiteeAPIClient {
  private client: AxiosInstance;

  constructor() {
    this.client = axios.create({
      baseURL: 'https://so.gitee.com',
      timeout: 30000, // 30 seconds timeout
      headers: {
        'User-Agent': 'grep-mcp-ts/1.0.0',
        'Accept': 'application/json'
      }
    });
  }

  /**
   * Search Gitee repositories using Gitee search API
   */
  async search(params: SearchParams): Promise<GiteeSearchResponse> {
    // Convert user-friendly params to Gitee API params
    const apiParams: GiteeAPIParams = {
      q: params.query
    };
    
    if (params.language) apiParams.language = params.language;
    if (params.repo) apiParams.repo = params.repo;
    if (params.path) apiParams.path = params.path;

    try {
      const response = await this.client.get<GiteeSearchResponse>('/', { params: apiParams });
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error)) {
        const axiosError = error as AxiosError;
        
        if (axiosError.code === 'ECONNABORTED' || axiosError.message.includes('timeout')) {
          throw new GiteeAPITimeoutError('Request to Gitee API timed out');
        }
        
        if (axiosError.response?.status === 429) {
          throw new GiteeAPIRateLimitError('Gitee API rate limit exceeded. Please wait before making another request.');
        }
        
        if (axiosError.response?.status === 404) {
          // Return empty response for 404 errors
          return {
            total_count: 0,
            incomplete_results: false,
            items: []
          };
        }
        
        throw new GiteeAPIError(`Gitee API request failed with status ${axiosError.response?.status || 'unknown'}: ${axiosError.message}`);
      }
      
      throw new GiteeAPIError(`Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}